
/**
 * 树转列表
 * @param {Array} tree 
 * @param {String} primaryKeyField 
 * @param {String} childrenField 
 * @param {String} parentIdField 
 * @returns 树转换后的列表
 */
export function treeToList(tree = [], childrenField = 'children') {
  const targetList = []

  for (const key in tree) {
    if (Object.hasOwnProperty.call(tree, key)) {
      const element = tree[key];
      targetList.push(element)

      const childrens = element[childrenField]
      if (childrens) {
        targetList.push(...treeToList(childrens))
      }
    }
  }
  return targetList
}
/**
 * 获取目标对象的所有父级列表
 * @param {*} list 
 * @param {*} primaryKeyValue 
 * @param {*} primaryKeyField 
 * @param {*} parentIdField 
 * @param {*} includeSelf 
 * @returns 
 */
export function getListParents(list = [], primaryKeyValue, primaryKeyField = "id", parentIdField = 'parentId', includeSelf = false) {

  const parents = []

  //目标对象
  const target = list.find(o => o[primaryKeyField] === primaryKeyValue)
  if (!target) {
    return parents
  }

  if (includeSelf) {
    parents.unshift(target);
  }
  //获取目标对象的父级
  let parent = list.find(p => p[primaryKeyField] === target[parentIdField])

  while (parent && parent[primaryKeyField] > 0) {
    //将新项目添加到数组的开头
    parents.unshift(parent)
    parent = list.find(p => p[primaryKeyField] === parent[parentIdField])
  }

  return parents;
}


export function getTreeParents(tree = [], primaryKeyValue, primaryKeyField = "id", parentIdField = 'parentId', childrenField = 'children') {
  const list = treeToList(tree, childrenField);
  return getListParents(list, primaryKeyValue, primaryKeyField, parentIdField, true)
}